<?php

// +----------------------------------------------------------------------
// | TAODUDU.COM  [ Simple Efficient Excellent ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016 http://www.taodudu.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: ubten <462193409@qq.com> http://www.ubten.com/
// +----------------------------------------------------------------------

namespace User\Controller;

use User\Controller\BaseController;

class AddressController extends BaseController {

    public function index() {
        $aModel = M('address');
        $where['user_id'] = session('user_id');
        if(IS_POST){
            $datas['user_id'] = session('user_id');
            $datas['true_name'] = I('true_name');
            $datas['area_info'] = I('area_info');
            $datas['city_id'] = I('city_id');
            $datas['area_id'] = I('area_id');
            $datas['address'] = I('address');
            $datas['mob_phone'] = I('mob_phone');
            $datas['is_default'] = 0;
            $a = M('address')->add($datas);
            if($a){
                $this->success('添加成功！',U('index'));
            }else{
                $this->error('添加失败！');
            }
        }
        $address = $aModel->where($where)->select();
        $this->assign('address', $address);
        $this->assign('active','address');
        $this->display();
    }
    
    public function defaultSite(){
        $address_id = 'address_id ='.I("address_id");
        $user_id = session('user_id');
        $address = M("address");
        $address->where("is_default = '1' AND user_id = $user_id")->save(array("is_default"=>'0'));
        $data['is_default'] = "1";
        $amend = $address->where($address_id)->data($data)->save();
        if($amend){
            $a['status'] = TRUE;
        }else{
            $a['status'] = FALSE;
            $a['msg'] = "设置失败！";
        }
        $this->ajaxReturn($a);
    }

    //修改收货地址
    public function modifying() {
        $address = M('address');
        $data = I('post.');
        $address_id['address_id'] = I('get.address_id');
        //若设置为默认地址则把其他地址修改为不默认
        if (I('is_default')) {
            $where['user_id'] = session('user_id');
            $address->where($where)->save(array('is_default' => 0));
        }
        $address->where($address_id)->data($data)->save();
        $this->success('修改成功', U('Address/index'));
    }

    //删除收货地址
    public function delAddress() {
        $address = M('address');
        $address_id['address_id'] = I('post.address_id');
        $address_id['user_id'] = session('user_id');
        $re = $address->where($address_id)->delete();
        if($re){
            $a['status'] = TRUE;
            $a['msg'] = "删除成功";
        }else{
            $a['status'] = FALSE;
            $a['msg'] = "删除失败";
        }
        $this->ajaxReturn($a);
    }

}
